//
//  SALoginVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/1/26.
//

#import "SALoginVC.h"
#import "HDTabBarController.h"
#import "SALoginAPI.h"
#import "NSString+MD5.h"
#import "SAPrepareRegisteredVC.h"
#import "SAPasswordVC.h"
#import "SAUserInfoTool.h"
#import "SAAppGetLastestVersionAPI.h"
#import "BubbleTableView.h"
#import "SAFMDBManger.h"
#import "AFNetworkReachabilityManager.h"
#import "SAServiceMarketListAPI.h"
#import "SAServiceMarketModel.h"

@interface SALoginVC ()<HTTPAPIDelegate,UITextFieldDelegate,NSURLSessionDelegate>

@property (nonatomic, strong) UITextField *userTf;
@property (nonatomic, strong) UITextField *passWordTf;
@property (nonatomic, strong) SALoginAPI *loginAPI;

@property(nonatomic ,weak) UILabel *managerLabel;
@property(nonatomic ,weak) UILabel *shopLabel;
@property(nonatomic ,strong) UIView *buleLine;
@property(nonatomic ,strong) UIView *line;

@property(nonatomic ,copy) NSString *userType;
@property(nonatomic ,strong) UIButton *forgetBtn;
@property(nonatomic ,strong) UIButton *keepBtn;
@property (nonatomic ,assign) BOOL selected;
@property (nonatomic, strong) SAAppGetLastestVersionAPI *appGetLastestVersionAPI;
@property (nonatomic, strong) BubbleTableView *nameBubbleView;
@property (nonatomic, strong) UIView *line2;
@property (nonatomic ,assign) BOOL getVersion;
@property (nonatomic, strong) SAServiceMarketListAPI *serviceMarketListAPI;

@end

@implementation SALoginVC
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getLastestVersion) name:AFNetworkingReachabilityDidChangeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(openPayment:) name:@"OpenPaymentLogin" object:nil];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSString *select = kSelectPsw;
    self.userType = kUserType;
    if (self.userType.length == 0){
        self.userType = @"1";
    }
    if ([select isEqualToString:@"1"]) {
        self.selected = YES;
    }else {
        self.selected = NO;
    }
    self.keepBtn.selected = self.selected;
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.loginAPI == api) {
        [MobClick event:@"APP_logon"];
        SAUserInfo *model = [SAUserInfo mj_objectWithKeyValues:data[@"data"]];
        [SAValueManger shareInStance].userInfo = model;
        [SAUserInfoTool saveModel:model];
        [[SAFMDBManger sharedInstance] updatePhoneData:self.userTf.text];
        [[NSUserDefaults standardUserDefaults] setObject:trimString(self.userTf.text) forKey:kLoginNameKey];
        [[NSUserDefaults standardUserDefaults] setObject:self.loginAPI.userType forKey:kUserTypeKey];
        [kUserDefault setObject:@"1" forKey:kAotuLoginKey];
        if (self.selected == YES) {
            [[NSUserDefaults standardUserDefaults] setObject:trimString(self.passWordTf.text) forKey:kPasswordKey];
            [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:kSelectPswKey];
        }else {
            [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:kPasswordKey];
            [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:kSelectPswKey];
        }
        [self.serviceMarketListAPI sendRequestToServerWithType:GET];//获取会员活动信息
    }else if (self.appGetLastestVersionAPI == api) {
        //获取线上版本
        if (self.getVersion == YES) {
            return;//只处理第一次获取版本
        }
        self.getVersion = YES;
        NSString *versionName = data[@"data"][@"versionName"];
        versionName = [versionName stringByReplacingOccurrencesOfString:@"." withString:@""];
        NSInteger versionInt = [versionName integerValue];
        //获取本地版本
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *versionName2 = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        versionName2 = [versionName2 stringByReplacingOccurrencesOfString:@"." withString:@""];
        NSInteger versionInt2 = [versionName2 integerValue];
        if (versionInt2 > versionInt) {
            NSString *userName = kLoginName;
            if (userName.length > 0 && ![userName isEqualToString:@"13728761589"]) {
                self.managerLabel.hidden = NO;
                self.shopLabel.hidden = NO;
                self.line.hidden = NO;
                self.buleLine.hidden = NO;
            }else {
                self.userType = @"1";
                [kUserDefault setObject:@"1" forKey:kReViewKey];
            }
        }else{
            [kUserDefault setObject:@"0" forKey:kReViewKey];
            self.managerLabel.hidden = NO;
            self.shopLabel.hidden = NO;
            self.line.hidden = NO;
            self.buleLine.hidden = NO;
            BOOL isForceUpdate = NO;
            if (versionInt != 999 && versionInt2 < versionInt) {
                NSInteger forceUpdate = [data[@"data"][@"forceUpdate"] integerValue];
                if (forceUpdate == 0) {
                    isForceUpdate = YES;
                    [self forcedUpdate];
                }else {
                    NSString *tipVersionInt = kTipVersionInt;
                    if ([tipVersionInt integerValue] < versionInt) {
                        [self tipRefresh:versionInt];
                    }
                }
            }
            if (isForceUpdate == NO) {
                [self automaticLogin];
            }
        }
    } else if (self.serviceMarketListAPI == api) {
        NSMutableArray<SAServiceMarketMenuModel *> *marr = [SAServiceMarketMenuModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        [SAValueManger shareInStance].noServiceMarket = (marr.count == 0);
        UIWindow *window =  [UIApplication sharedApplication].keyWindow;
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[HDTabBarController new]];
        window.rootViewController = nav;
        [window makeKeyAndVisible];
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    if (self.loginAPI == api) {
        [kUserDefault setObject:@"" forKey:kPasswordKey];
    } else if (self.serviceMarketListAPI == api) {
        UIWindow *window =  [UIApplication sharedApplication].keyWindow;
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:[HDTabBarController new]];
        window.rootViewController = nav;
        [window makeKeyAndVisible];
    }
}

-(void)forcedUpdate {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"message:@"由于版本改动较大,如继续使用，部分功能可能会有异常" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"现在升级" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/yi-ka-tongbic-ban/id1551743808?l=en&mt=8"] options:[NSDictionary dictionary] completionHandler:nil];
        [self forcedUpdate];
    }]];
}

-(void)tipRefresh:(NSInteger)versionInt {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"message:@"您好,有新版本上线了" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alert animated:YES completion:nil];
    [alert addAction:[UIAlertAction actionWithTitle:@"不再提示" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [kUserDefault setObject:[NSString stringWithFormat:@"%zd",versionInt] forKey:kTipVersionIntKey];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"现在升级" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/yi-ka-tongbic-ban/id1551743808?l=en&mt=8"] options:nil completionHandler:nil];
    }]];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    return YES;
}

- (void)textFieldEditChanged:(UITextField*)textField {
    if (self.userTf == textField) {
        [[SAFMDBManger sharedInstance] readAllPhoneData:textField.text AndDataArr:^(NSMutableArray *phoneMarr) {
            if (phoneMarr.count > 0) {
                [self showBubbleView:phoneMarr];
            }else {
                [self.nameBubbleView hide];
                self.nameBubbleView = nil;
            }
        }];
    }
}

-(void)showBubbleView:(NSMutableArray *)marr {
    if (!self.nameBubbleView) {
        self.nameBubbleView = [[BubbleTableView alloc] initWithLocation:(BubbleLocationDown) bubbleAlignment:(BubbleAlignmentCenter) width:225 height:40 * 4 cellClickBlock:^(NSInteger row, NSString * _Nonnull rowString, NSArray *fromDataArray) {
            self.userTf.text = rowString;
        } hideBlock:^{
            self.nameBubbleView = nil;
        }];
        [self.nameBubbleView showWithTargetView:self.line2 maskSuperView:self.view];
        [self.nameBubbleView updateBubble:marr fromDataArray:marr];// 更新气泡弹框
        self.nameBubbleView.bubbleCellHeight = 40;
        self.nameBubbleView.isBubbleScrollEnabled = YES;
        self.nameBubbleView.bubbleCellTextAlignment = NSTextAlignmentCenter;
    }else {
        [self.nameBubbleView updateBubble:marr fromDataArray:marr];// 更新气泡弹框
    }
}

-(void)automaticLogin{
    NSString *userName = kLoginName;
    NSString *passWord = kPassword;
    NSString *select = kSelectPsw;
    NSString *aotuLogin = kAotuLogin;
    self.userType = kUserType;
    if (self.userType.length == 0){
        self.userType = @"1";
    }
    if ([select isEqualToString:@"1"]) {
        self.selected = YES;
    }else {
        self.selected = NO;
    }
    self.keepBtn.selected = self.selected;
    if (userName.length > 0 && passWord.length > 0 && aotuLogin.length > 0) {
        self.loginAPI.userType = kUserType;
        self.loginAPI.userName = userName;
        self.loginAPI.password = [NSString stringToMD5:trimString(passWord)];
        //自动登录-权限问题需要暂时屏蔽
        //        [self.loginAPI sendRequestToServerWithActivityViewAndMask:POST];
    }
}

-(void)clickedForgetBtn {
    SAPasswordVC *pushVC = [SAPasswordVC new];
    [self.navigationController pushViewController:pushVC animated:YES];
}
-(void)clickedRegisteredBtn {
    SAPrepareRegisteredVC *pushVC = [SAPrepareRegisteredVC new];
    [self.navigationController pushViewController:pushVC animated:YES];
}

-(void)keepBtnClick:(id)sender
{
    _selected = !_selected;
    self.keepBtn.selected = _selected;
}

-(void)clickedLoginBtn {
    // 1877 3715 713
    // 189 2341 1800
    // 13620958386
    
    if(trimString(self.userTf.text).length <= 0){
        [Prompt popPromptViewWithMsg:@"请输入手机号码!" duration:2];
        return;
    }
    if(trimString(self.userTf.text).length != 11){
        [Prompt popPromptViewWithMsg:@"请输入11位手机号码!" duration:2];
        return;
    }
    
    if(!(trimString(self.passWordTf.text).length >=6 &&trimString(self.passWordTf.text).length <= 20)){
        [Prompt popPromptViewWithMsg:@"请输入6-20 位数字，字母组合密码 !" duration:2];
        return;
    }
    
    self.loginAPI.userType = self.userType;
    self.loginAPI.userName = trimString(self.userTf.text);
    self.loginAPI.password = [NSString stringToMD5:trimString(self.passWordTf.text)];
    [self.loginAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(void)clickedFormalBtn {
    [Prompt popPromptViewWithMsg:@"网络切换为线上" duration:2];
    [[NSUserDefaults standardUserDefaults] setValue:@"https://retail.fuyungroup.com" forKey:@"ServerHost"];
    [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"ServerPort"];
}

-(void)clickedFhroughBtn {
    [Prompt popPromptViewWithMsg:@"网络切换为内网穿透" duration:2];
    [[NSUserDefaults standardUserDefaults] setValue:@"http://fuyun.free.idcfengye.com" forKey:@"ServerHost"];
    [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"ServerPort"];
}

//通知
-(void)getLastestVersion {
    if (self.getVersion != YES) {
        [self.appGetLastestVersionAPI sendRequestToServerWithType:POST];
    }
}

- (void)openPayment:(NSNotification*)notification {
    NSDictionary *object = notification.object;
    self.loginAPI.userType = @"1";
    self.loginAPI.userName = object[@"iphone"];
    self.loginAPI.password = [NSString stringToMD5:object[@"passWord"]];
    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:kRegisteredOpenPaymentKey];
    [self.loginAPI sendRequestToServerWithActivityViewAndMask:POST];
}

// 实现NSURLSessionDelegate方法
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
    }
}

-(void)initUI {
    
    self.view.backgroundColor = kLineColor;
    
    UIImageView *topImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Login_top"]];
    topImageV.frame = SARectMake(0, 0, kBaseScreenWidth, 165 + DifferenceHeight);
    [self.view addSubview:topImageV];
    
    UILabel *tipLab = [[UILabel alloc] initWithFrame:SARectMake(24, 70 + DifferenceHeight, 200, 20)];
    tipLab.text = @"Hello!";
    tipLab.font = kBFont(18);
    tipLab.textColor = [UIColor whiteColor];
    tipLab.textAlignment = NSTextAlignmentLeft;
    [self.view  addSubview:tipLab];
    
    UILabel *tipLab2 = [[UILabel alloc] initWithFrame:SARectMake(24, 97 + DifferenceHeight, kBaseScreenWidth, 20)];
    tipLab2.text = @"欢迎登录衣点通";
    tipLab2.font = kBFont(18);
    tipLab2.textColor = [UIColor whiteColor];
    tipLab2.textAlignment = NSTextAlignmentLeft;
    [self.view  addSubview:tipLab2];
    
    UIView *whiteView = [[UIView alloc] initWithFrame:SARectMake(15, 128 + DifferenceHeight, 345, 400)];
    whiteView.backgroundColor = [UIColor whiteColor];
    whiteView.layer.cornerRadius = kScaleNum(5);
    whiteView.layer.masksToBounds = YES;
    [self.view addSubview:whiteView];
    
    UIImageView *titleImage = [[UIImageView alloc] initWithFrame:SARectMake(141, 35, 63, 17)];
    titleImage.image = [UIImage imageNamed:@"new_ydt"];
    [whiteView addSubview:titleImage];
    
    UILabel *managerLabel = [[UILabel alloc] initWithFrame:SARectMake(60, 60, 112.5, 50)];
    managerLabel.textAlignment = NSTextAlignmentCenter;
    managerLabel.textColor = kBlackColor;
    managerLabel.font = kFont(16);
    managerLabel.text = @"老板";
    managerLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *managerLabelTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(managerLabelTapEvent)];
    [managerLabel addGestureRecognizer:managerLabelTap];
    [whiteView addSubview:managerLabel];
    self.managerLabel = managerLabel;
    managerLabel.hidden = YES;
    
    UILabel *shopLabel = [[UILabel alloc] initWithFrame:SARectMake(172.5, 60, 112.5, 50)];
    shopLabel.textAlignment = NSTextAlignmentCenter;
    shopLabel.textColor = kBlackColor;
    shopLabel.font =  kFont(16);
    shopLabel.text = @"店员";
    shopLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *shopLabelTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shopLabelTapEvent)];
    [shopLabel addGestureRecognizer:shopLabelTap];
    [whiteView addSubview:shopLabel];
    self.shopLabel = shopLabel;
    shopLabel.hidden = YES;

    UIView *line = [[UIView alloc] initWithFrame:SARectMake(60, 110, 225, 1)];
    line.backgroundColor = kColor(230, 230, 230, 1);
    [whiteView addSubview:line];
    self.line = line;
    line.hidden = YES;

    UIView *buleLine = [[UIView alloc] initWithFrame:SARectMake(60, 110, 112.5, 1)];
    buleLine.backgroundColor = kBuleColor;
    [whiteView addSubview:buleLine];
    self.buleLine = buleLine;
    buleLine.hidden = YES;
    
    UIImageView *peopleImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Login_people"]];
    peopleImageV.frame = SARectMake(60, 140, 17, 17);
    [whiteView addSubview:peopleImageV];

    UITextField *userNameTf = [[UITextField alloc] initWithFrame:SARectMake(90, 125, 195, 47)];
    userNameTf.placeholder = @"请输入您的账号";
    userNameTf.font = kFont(15);
    userNameTf.textColor = kBlackColor;
    userNameTf.textAlignment = NSTextAlignmentLeft;
    userNameTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    [whiteView addSubview:userNameTf];
    userNameTf.keyboardType = UIKeyboardTypeNumberPad;
    self.userTf = userNameTf;
    userNameTf.delegate = self;
    [userNameTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    
    if ([[NSUserDefaults standardUserDefaults] stringForKey:kLoginNameKey].length >0) {
        self.userTf.text = [[NSUserDefaults standardUserDefaults] stringForKey:kLoginNameKey];
    }

    UIView *line2 = [[UIView alloc] initWithFrame:SARectMake(60, 167, 225, 1)];
    line2.backgroundColor = kLineColor;
    [whiteView addSubview:line2];
    self.line2 = line2;
    
    UIImageView *lockImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Login_lock"]];
    lockImageV.frame = SARectMake(60, 197, 17, 17);
    [whiteView addSubview:lockImageV];

    UITextField *passWordTf = [[UITextField alloc] initWithFrame:SARectMake(90, 182, 195, 47)];
    passWordTf.placeholder = @"请输入您的密码";
    passWordTf.font = kFont(15);
    passWordTf.textColor = kBlackColor;
    passWordTf.textAlignment = NSTextAlignmentLeft;
    passWordTf.secureTextEntry = YES;
    passWordTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    [whiteView addSubview:passWordTf];
    self.passWordTf = passWordTf;

    UIView *line3 = [[UIView alloc] initWithFrame:SARectMake(60, 224, 225, 1)];
    line3.backgroundColor = kLineColor;
    [whiteView addSubview:line3];
    
    UIButton *keepBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    keepBtn.frame = SARectMake(60, 230, 80, 30);
    [keepBtn setImage:[UIImage imageNamed:@"lohin_newKeep_n"] forState:UIControlStateNormal];
    [keepBtn setImage:[UIImage imageNamed:@"lohin_newKeep_s"] forState:UIControlStateSelected];
    keepBtn.selected = _selected;
    [keepBtn setTitleColor:kColor(200, 200, 200, 1) forState:UIControlStateNormal];
    [keepBtn setTitleColor:kColor(200, 200, 200, 1) forState:UIControlStateSelected];
    [keepBtn setTitle:@"  记住密码" forState:UIControlStateNormal];
    [keepBtn addTarget:self action:@selector(keepBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    keepBtn.titleLabel.font = kFont(14);
    keepBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [whiteView addSubview:keepBtn];
    self.keepBtn = keepBtn;
    
    UIButton *forgetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    forgetBtn.frame = SARectMake(345 - 140, 230, 80, 30);
    [forgetBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [forgetBtn setTitleColor:kColor(200, 200, 200, 1) forState:UIControlStateNormal];
    forgetBtn.titleLabel.font = kFont(14);
    forgetBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [forgetBtn addTarget:self action:@selector(clickedForgetBtn) forControlEvents:UIControlEventTouchUpInside];
    [whiteView addSubview:forgetBtn];

    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame = SARectMake(60, 280, 225, 35);
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"Login_btn_1"] forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginBtn.titleLabel.font = kFont(15);
    [loginBtn addTarget:self action:@selector(clickedLoginBtn) forControlEvents:UIControlEventTouchUpInside];
    [whiteView addSubview:loginBtn];
    
    if ([[NSUserDefaults standardUserDefaults] stringForKey:kPasswordKey].length > 0) {
        self.passWordTf.text = [[NSUserDefaults standardUserDefaults] stringForKey:kPasswordKey];
        keepBtn.selected = YES;
        self.selected = YES;
    }
    
    NSString *userType = kUserType;
    if (userType.length == 0) {
        userType = @"1";
    }
    if ([userType isEqualToString:@"1"]) {
        
    }else {
        [self shopLabelTapEvent];
    }

    UIButton *registeredBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    registeredBtn.frame = SARectMake(60, 350, 225, 35);
    [registeredBtn setTitle:@"立即注册" forState:UIControlStateNormal];
    [registeredBtn setBackgroundImage:[UIImage imageNamed:@"Login_btn_2"] forState:UIControlStateNormal];
    [registeredBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
    registeredBtn.titleLabel.font = kFont(15);
    [registeredBtn addTarget:self action:@selector(clickedRegisteredBtn) forControlEvents:UIControlEventTouchUpInside];
    [whiteView addSubview:registeredBtn];
    
    
    UIButton *formalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    formalBtn.frame = CGRectMake(20, kScreenHeight - 80, 80, 40);
    [formalBtn setTitle:@"线上" forState:UIControlStateNormal];
    [formalBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    formalBtn.titleLabel.font = kFont(18);
    formalBtn.backgroundColor = kBuleColor;
    [formalBtn addTarget:self action:@selector(clickedFormalBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:formalBtn];
    
    UIButton *throughBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    throughBtn.frame = CGRectMake(kScreenWidth - 100, kScreenHeight - 80, 80, 40);
    [throughBtn setTitle:@"内网穿透" forState:UIControlStateNormal];
    [throughBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    throughBtn.titleLabel.font = kFont(18);
    throughBtn.backgroundColor = kBuleColor;
    [throughBtn addTarget:self action:@selector(clickedFhroughBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:throughBtn];
    
    if (kIsTestServer == 1) {
        formalBtn.hidden = YES;
        throughBtn.hidden = YES;
    } else {
        //处理内网穿透
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        config.TLSMinimumSupportedProtocol = kTLSProtocol12;
        config.URLCache = nil;
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    }
    
    [[NSUserDefaults standardUserDefaults] setValue:@"http://192.168.111.166" forKey:@"ServerHost"];
    [[NSUserDefaults standardUserDefaults] setValue:@"9081" forKey:@"ServerPort"];
    
    NSString *userName = kLoginName;
    if (userName.length > 0 && ![userName isEqualToString:@"13728761589"]) {
        self.managerLabel.hidden = NO;
        self.shopLabel.hidden = NO;
        self.line.hidden = NO;
        self.buleLine.hidden = NO;
    }
    
    [self.appGetLastestVersionAPI sendRequestToServerWithType:POST];
}

-(void)managerLabelTapEvent
{
    self.managerLabel.layer.borderColor =[kColor(127, 57, 26, 1) CGColor];
    self.shopLabel.layer.borderColor = [kColor(127, 57, 26, 1) CGColor];
    self.userType = @"1";
    self.forgetBtn.hidden = NO;
    self.userTf.placeholder = @"请输入手机号";
    [UIView animateWithDuration:0.2 animations:^{
        self.buleLine.x = kScaleNum(60);
    }];
}

-(void)shopLabelTapEvent
{
    self.shopLabel.layer.borderColor =[kColor(127, 57, 26, 1) CGColor];
    self.managerLabel.layer.borderColor =[kColor(255, 255, 255, 1) CGColor];
    self.userType = @"3";
    self.forgetBtn.hidden = YES;
    self.userTf.placeholder = @"请输入用户名";
    [UIView animateWithDuration:0.2 animations:^{
        self.buleLine.x = kScaleNum(172.5);
    }];
}

-(SALoginAPI *)loginAPI {
    if (!_loginAPI) {
        _loginAPI = [SALoginAPI apiWithDelegate:self];
    }
    return _loginAPI;
}

-(SAAppGetLastestVersionAPI *)appGetLastestVersionAPI {
    if (!_appGetLastestVersionAPI) {
        _appGetLastestVersionAPI = [SAAppGetLastestVersionAPI apiWithDelegate:self];
    }
    return _appGetLastestVersionAPI;
}

-(SAServiceMarketListAPI *)serviceMarketListAPI {
    if (!_serviceMarketListAPI) {
        _serviceMarketListAPI = [SAServiceMarketListAPI apiWithDelegate:self];
    }
    return _serviceMarketListAPI;
}

-(void)dealloc
{
    HDLog(@"%@ 控制器已经被释放",NSStringFromClass([self class]));
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
